package EBM.BLL;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;

//import org.eclipse.swt.widgets.MessageBox;




public class SocketConnection {
	// 从配置文件中获取端口号4321
	private static int port = Integer.parseInt(ParseProperties.getProperties("port"));
	// 从配置文件中获取服务器地址127.0.0.1
	private static String address =ParseProperties.getProperties("address");
	// 声明客户端Socket对象socket
	private static Socket socket = null;
	// 声明客户器端数据输入输出流
	private static ObjectInputStream in;
	private static ObjectOutputStream out;
	// 参数 to Server
	private static String cmd = null;
	// 参数 input
	private static Object tmp = null;
	private static ArrayList<Object> listIn = null;
	private static ArrayList<Object> listOut = null;
	

		
	public SocketConnection() {
		
	}

	public static void DataTransmission( ) throws IOException,
			ClassNotFoundException {
		
		try {
			// 创建客户端socket，服务器地址取address，端口号为4321
			socket = new Socket(address, port);
			// 声明输入输出流
			out = new ObjectOutputStream(socket.getOutputStream());
			in = new ObjectInputStream(socket.getInputStream());

			// 声明输入流存储的数组
			listIn = new ArrayList<Object>();

			// 发送操作命令cmd
			out.writeObject(cmd);
			// 发送操作数据
			for (int i = 0; i < listOut.size(); i++)
				out.writeObject(listOut.get(i));
			// 发送结束标识
			out.writeObject("_E_N_D_");
			// 清空输出流
			out.flush();
			listOut.clear();

			// 接受服务器的返回数据
			tmp = in.readObject();
			while (!tmp.toString().equals("_E_N_D_")) {
				listIn.add(tmp);
				tmp = in.readObject();
			}

		
			
		} catch (UnknownHostException e) {
			listIn = new ArrayList<Object>();
			System.out.println("服务器连接出错: 未知的主机");
			//box.setMessage("服务器连接出错: 未知的主机");
			//box.open();
			e.printStackTrace();
		} catch (IOException e) {
			listIn = new ArrayList<Object>();
			System.out.println("服务器连接出错: I/O错误");
			//box.setMessage("服务器连接出错: I/O错误");
			//box.open();
			e.printStackTrace();
		} finally {
			socket.close();
			System.out.println("A connection closing...");
		}
	}

	public static int getPort() {
		return port;
	}

	public static void setPort(int port) {
		SocketConnection.port = port;
	}

	public static String getAddress() {
		return address;
	}

	public static void setAddress(String address) {
		SocketConnection.address = address;
	}

	public static String getCmd() {
		return cmd;
	}

	public static void setCmd(String cmd) {
		SocketConnection.cmd = cmd;
	}

	public static ArrayList<Object> getListIn() {
		return listIn;
	}

	public static void setListIn(ArrayList<Object> listIn) {
		SocketConnection.listIn = listIn;
	}

	public static ArrayList<Object> getListOut() {
		return listOut;
	}

	public static void setListOut(ArrayList<Object> listOut) {
		SocketConnection.listOut = listOut;
	}
	
}
